import axios from 'axios'
import store from '@/store/index'
import { Message } from 'element-ui'
import router from '@/router'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = store.state.user.token
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code !== 10000) {
      Message({ type: 'error', message: response.data.msg })
      return Promise.reject(response.data)
    }
    return response.data
  },
  error => {
    Message({ type: 'error', message: `${error.response.data.msg}` })
    console.dir(error)
    // 当接口返回401错误时，跳转登录页面
    if (error.response.status === 401) {
      store.commit('user/clearUserInfo')
      router.push({ path: '/login' })
    }
    return Promise.reject(error)
  }
)

export default service
